package com.yzkj.cpjxc.business.framework.utils;

import javax.sql.rowset.serial.SerialClob;
import javax.sql.rowset.serial.SerialException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;

/**
 * 大字段工具类
 */
public class ClobUtils {
	
	/**
	 * @description: 字符类型转成Clob类型
	 */
	public static Clob string2clob(String str) throws SerialException, SQLException {
		if (str == null) {
			return null;
		}
		return new SerialClob(str.toCharArray());
	}

	/**
	 * @description: Clob类型转成字符类型
	 */
	public static String clob2String(Clob c) {
		if (c == null) {
			return "";
		}
		try {
			StringBuffer sb = new StringBuffer();
			Reader r = c.getCharacterStream();
			int ch;
			while ((ch = r.read()) != -1) {
				sb.append((char) ch);
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @description: Clob类型转成字符类型(超过指定长度就用...代替)
	 */
	public static String clob2Brief(Clob c, int length) {
		if (c == null) {
			return "";
		}
		try {
			StringBuffer sb = new StringBuffer();
			Reader r = c.getCharacterStream();
			int count = 0;
			int ch;
			boolean finish = true;
			while ((ch = r.read()) != -1) {
				sb.append((char) ch);
				if (count >= length) {
					finish = false;
					break;
				}
				count++;
			}
			if (!finish) {
				sb.append("...");
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
